<template>
  <view v-if="visible" class="poster-modal">
    <view class="poster-overlay" @tap="closeModal"></view>
    <view class="poster-content">
      <!-- 背景图片 -->
      <image
        class="poster-bg-image"
        src="@/static/assets/source/post-bg.png"
        mode="contain"
      />
      <!-- 海报内容卡片，右上角对齐 -->
      <view class="poster-card-wrapper">
        <view class="poster-card">
          <!-- 图片 -->
          <image 
            :src="getImageUrl()" 
            class="poster-image" 
            mode="aspectFill"
          />
          
          <!-- 信息 -->
          
          <view class="poster-info">
            <view class="title">{{ getTitle() }}</view>
            
            <!-- 地址信息 -->
            <view class="address-row">
              <image src="/static/assets/parkInfo/park-info-row5.png" class="location-icon" />
              <text class="address-text">{{ getAddress() }}</text>
            </view>
            
            <!-- 价格信息 -->
            <view class="price-row" v-if="type === 'warehouse'">
              <text class="price-text">¥{{ getPrice() }}元/m²/天</text>
              <text class="price-tip">起(具体面议)</text>
              <text class="rentable-area">招租面积: {{ formatArea(getArea()) }}</text>
            </view>
            
            <!-- 园区价格信息 -->
            <view class="price-row" v-if="type === 'park'">
              <text class="price-text">¥{{ getPrice() }}元/m²/天</text>
              <text class="price-tip">起(具体面议)</text>
              <text class="rentable-area">招租面积: {{ formatArea(getArea()) }}</text>
            </view>
          <!-- 园区规模 -->
          <uni-card spacing="0" padding="10rpx" margin="0rpx">
            <view class="card-header">
              <image src="/static/assets/parkInfo/park-info-row1.png" class="addr-icon"
                style="width: 18rpx;height: 23rpx;" />
              <text class="card-title">园区规模</text>
            </view>
            <view class="detail-section">
              <view class="detail-grid">
                <view class="detail-item" v-for="(item, index) in getDetailItems()" :key="index">
                  <view class="detail-label">{{ item.label }}</view>
                  <view class="detail-value">{{ item.value }}</view>
                </view>
              </view>
            </view>
          </uni-card>
               <!-- 园区规模 -->
          <uni-card spacing="0" padding="10rpx" margin="10rpx 0rpx">
            <view class="card-header">
              <image src="/static/assets/parkInfo/park-info-row1.png" class="addr-icon"
                style="width: 18rpx;height: 23rpx;" />
              <text class="card-title">招商联系人：{{(data.manager || data.parkInfo.manager || "-") +" "+(data.contactPhone || data.parkInfo.contactPhone || "-")}}</text>
            </view>
          </uni-card>
          </view>
        </view>
        <!-- 关闭按钮，右上角对齐 -->
        <view class="close-btn" @tap="closeModal">
          <image src="/static/assets/source/postTopIcon.png" class="close-icon" />
        </view>
      </view>
    </view>
    <!-- 操作按钮 -->
    <view class="poster-actions">
      <button class="action-btn save-btn" @tap="saveToAlbum" :disabled="saving">
        <image src="/static/assets/source/down-save-icon.png" class="btn-icon" />
        {{ saving ? '生成中...' : '保存到相册' }}
      </button>
    </view>
    <!-- Canvas 组件 -->
    <PosterCanvas 
      ref="posterCanvas"
      :type="type"
      :data="data"
      :showCanvas="showCanvas"
      @poster-generated="onPosterGenerated"
      @saved="onPosterSaved"
      @error="onPosterError"
    />
  </view>
</template>

<script>
import PosterCanvas from './PosterCanvas.vue'
export default {
  name: 'PosterModal',
  components: {
    PosterCanvas
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'warehouse', // 'warehouse' 或 'park'
      validator: value => ['warehouse', 'park'].includes(value)
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      saving: false,
      showCanvas: false
    }
  },
  methods: {
    closeModal() {
      this.$emit('close')
    },
    
    // 获取图片URL - 修复字段映射
    getImageUrl() {
      if (this.type === 'warehouse') {
        // 仓库图片字段映射
        return this.data.thumbnailUrl || 
               this.data.coverImage || 
               this.data.image || 
               this.data.warehouseImage ||
               '/static/assets/warehouse/warehouse-default.jpg'
      } else {
        // 园区图片字段映射
        return this.data.thumbnailUrl || 
               this.data.parkImage || 
               this.data.image || 
               this.data.coverImage ||
               '/static/assets/park/park-default.jpg'
      }
    },
    
    // 获取标题 - 修复字段映射
    getTitle() {
      if (this.type === 'warehouse') {
        // 仓库标题字段映射
        return this.data.warehouseName || 
               this.data.name || 
               this.data.title ||
               '仓库名称'
      } else {
        // 园区标题字段映射
        return this.data.parkName || 
               this.data.name || 
               this.data.title ||
               '园区名称'
      }
    },
    
    // 获取地址 - 修复字段映射
    getAddress() {
      if (this.type === 'warehouse') {
        // 仓库地址字段映射
        return this.data.address || 
               this.data.location || 
               this.data.fullAddress ||
               '仓库地址'
      } else {
        // 园区地址字段映射
        return this.data.location || 
               this.data.address || 
               this.data.fullAddress ||
               '园区地址'
      }
    },
    
    // 获取价格 - 修复字段映射
    getPrice() {
      return this.data.rentalPrice || 
             this.data.price || 
             this.data.rentPrice ||
             '0.9'
    },
    
    // 获取面积 - 修复字段映射
    getArea() {
      if (this.type === 'warehouse') {
        // 仓库面积字段映射
        return this.data.areaSize || 
               this.data.rentableArea || 
               this.data.area ||
               1000
      } else {
        // 园区面积字段映射
        return this.data.rentableArea || 
               this.data.areaSize || 
               this.data.area ||
               21000
      }
    },
    
    // 获取详细信息 - 修复字段映射
    getDetailItems() {
      if (this.type === 'warehouse') {
        return [
          { 
            label: '仓库类型', 
            value: this.data.warehouseType?.typeName || 
                   this.data.warehouseType || 
                   this.data.type ||
                   '' 
          },
          { 
            label: '层高', 
            value: this.data.floorHeight || 
                   this.data.height ||
                   '' 
          },
          { 
            label: '地面承重', 
            value: this.data.floorLoad || 
                   this.data.loadCapacity ||
                   '²' 
          },
          { 
            label: '月台数量', 
            value: (this.data.platformCount || 
                   this.data.platforms || 
                   '-') 
          }
        ]
      } else {
        return [
          { 
            label: '总占地面积', 
            value: this.formatArea(this.data.totalArea || 
                                  this.data.totalAreaSize || 
                                  0) 
          },
          { 
            label: '建筑面积', 
            value: this.formatArea(this.data.buildingArea || 
                                  this.data.buildingAreaSize || 
                                  0) 
          },
          { 
            label: '仓库类型', 
            value: this.data.warehouseType || 
                   this.data.type ||
                   '' 
          },
          { 
            label: '层高', 
            value: this.data.floorHeight || 
                   this.data.height ||
                   '' 
          }
        ]
      }
    },
    
    formatArea(value) {
      const num = Number(value || 0)
      if (!num) return '0m²'
      if (num >= 100000) {
        const wan = num / 10000
        return `${this.toFixedSafe(wan, 0)}万m²`
      }
      return `${this.toFixedSafe(num, 0)}m²`
    },
    
    toFixedSafe(n, d) {
      const m = Math.pow(10, d)
      return (Math.round(n * m) / m).toFixed(d)
    },
    
    async saveToAlbum() {
      try {
        this.saving = true
        this.showCanvas = true
        
        // 等待下一个tick确保canvas已渲染
        await this.$nextTick()
        
        // 生成海报
        await this.$refs.posterCanvas.generatePoster()
        
      } catch (error) {
        this.saving = false
        console.error('生成海报失败:', error)
        uni.showToast({
          title: '生成失败',
          icon: 'none'
        })
      }
    },
    
    // 海报生成完成
    onPosterGenerated() {
      // 保存到相册
      this.$refs.posterCanvas.saveToAlbum()
    },
    
    // 海报保存成功
    onPosterSaved() {
      this.saving = false
      this.showCanvas = false
      this.$emit('saved')
    },
    
    // 海报生成错误
    onPosterError(error) {
      this.saving = false
      this.showCanvas = false
      console.error('海报生成错误:', error)
    },
    
    bookNow() {
      this.closeModal()
      // 触发预约事件
      this.$emit('book')
    },

    // 绘制斜长方形虚影效果
    drawShadowEffect(ctx, canvasW) {
      const shadowY = this.canvasHeight - 140 // 按钮上方
      const shadowX = canvasW / 2 - 100 // 居中
      
      // 保存当前状态
      ctx.save()
      
      // 设置变换
      ctx.translate(shadowX + 100, shadowY)
      ctx.rotate(-3 * Math.PI / 180) // -3度
      ctx.translate(-100, 0)
      
      // 绘制虚影
      this.drawRoundedRect(ctx, 0, 0, 200, 20, 10)
      const gradient = ctx.createLinearGradient(0, 0, 200, 0)
      gradient.addColorStop(0, 'rgba(0, 0, 0, 0.1)')
      gradient.addColorStop(0.5, 'rgba(0, 0, 0, 0.05)')
      gradient.addColorStop(1, 'rgba(0, 0, 0, 0.1)')
      ctx.setFillStyle(gradient)
      ctx.fill()
      
      // 恢复状态
      ctx.restore()
    }
  }
}
</script>

<style scoped>
.poster-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.poster-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.poster-content {
  position: relative;
  width: 652rpx;
  height: 920rpx;
  display: flex;
  flex-direction: column;
}

.poster-bg-image {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  border-radius: 16rpx;
  object-fit: fill;
  pointer-events: none;
}

.poster-card-wrapper {
  position: absolute;
  top: 20rpx;
  right: 0;
  width: 620rpx !important;
  height: 850rpx !important;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
}

.poster-card {
  flex: 1;
  padding: 20rpx;
  position: relative;
  width: 100%;
  box-sizing: border-box;
  background-color: #ffffff;
    border-radius: 16rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
}

.poster-image {
  width: 100%;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.poster-info {
  padding: 0 10rpx;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 12rpx;
}

.address-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.location-icon {
  width: 18rpx;
  height: 24rpx;
  margin-right: 8rpx;
}

.address-text {
  font-size: 24rpx;
  color: #666666;
  flex: 1;
}

.price-row {
  margin-bottom: 20rpx;
}

.price-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #C02C38;
  margin-right: 8rpx;
}

.price-tip {
  font-size: 20rpx;
  color: #999999;
  margin-right: 16rpx;
}

.rentable-area {
  font-size: 22rpx;
  color: #666666;
}

.detail-section {
  margin-top: 20rpx;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16rpx;
}

.detail-item {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 16rpx;
  border: 1rpx solid #e9ecef;
}

.detail-label {
  font-size: 20rpx;
  color: #666666;
  margin-bottom: 8rpx;
}

.detail-value {
  font-size: 24rpx;
  color: #333333;
  font-weight: 500;
}

.poster-actions {
  margin-top: 20rpx;
  padding: 20rpx;
  width: 100%;
}

.action-btn {
  width: 300rpx;
  height: 80rpx;
  border-radius: 12rpx;
  border: 2rpx solid #ffffff;
  background: rgba(128, 128, 128, 0.3);
  font-size: 28rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  color: #ffffff;
}

.save-btn {
  background: rgba(128, 128, 128, 0.3);
  color: #ffffff;
}

.save-btn:disabled {
  background: #cccccc;
  color: #999999;
}

.btn-icon {
  width: 32rpx;
  height: 32rpx;
}

.close-btn {
  position: absolute;
  top: -25rpx;
  right: -25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.close-icon {
  width: 85rpx;
  height: 85rpx;
}

.card-header {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	/* margin-bottom: 16rpx; */
}

.card-title {
	font-size: 24rpx;
	font-weight: 700;
}

.card-header.header-link .link {
	color: #C02C38;
	font-size: 24rpx;
}

.addr-icon {
	margin-right: 8rpx;
	object-fit: contain !important;
}
</style>
